package br.com.vendaext.gerencial.integracao;
import java.util.HashMap;
import java.util.Map;

import javax.faces.context.FacesContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean;

/**
 * Factory bean to return a <code>org.hibernate.SessionFactory</code> object.
 * This class is injected with a map of SessionFactory objects and determines at
 * runtime which SessionFactory to return. The logic for returning a
 * SessionFactory is based on the current user on whose behalf the request is
 * made. This is set/determined in the UserContext class via a
 * <code>ThreadLocal</code> property.
 * 
 * @author Arthur Loder
 */
public class MapSessionFactoryBean extends AnnotationSessionFactoryBean{
	
	
  /**
   * Loggger for class.
   */
  private Log log = LogFactory.getLog(getClass());
	
  /**
   * Map of <code>SessionFactory</code> objects. This FactoryBean class will
   * return one of the SessionFactory classes in this map.
   */
  private Map<String, SessionFactory> sessionFactoryMap;

  /**
   * Sets the map of SessionFactory objects.
   * 
   * @param sessionFactoryMap the SessionFactory map.
   */
  public void setSessionFactoryMap(Map<String, SessionFactory> sessionFactoryMap) {
    this.sessionFactoryMap = sessionFactoryMap;
  }

  /**
   * Returns the appropriate SessionFactory based on the user. If the user is
   * an administrator (i.e., the user's username begins with 'admin_') then
   * the 'adminSessionFactory' is returned. Otherwise, the
   * 'restrictedSessionFactory' is returned.
   */
  
//  public Object getObject() throws Exception {
//    // Determine the current user's name from this class that holds the current user
////    String currentUsername = UserContext.getCredentialsForCurrentThread();
////    log.debug("Current username: '" + currentUsername + "'");
//		
////    if (currentUsername != null && currentUsername.startsWith(ADMIN_PREFIX)) {
////      // If the user is an admin return adminSessionFactory
////      log.info("Returning 'adminSessionFactory'");
////      return sessionFactoryMap.get("adminSessionFactory");
////    }
//    
//    // Otherwise, return restrictedSessionFactory
//    log.info("Returning 'restrictedSessionFactory'");
//    return sessionFactoryMap.get("restrictedSessionFactory");
//
//  }

  /**
   * Returns org.hibernate.SessionFactory class.
   */
  public Class getObjectType() {
    return SessionFactory.class;
  }

  /**
   * This class is a non-singleton because the particular SessionFactory to
   * return is determined at runtime and can vary during the application
   * lifecycle as different users log in. Therefore, the result of this bean
   * should not be cached.
   */
  public boolean isSingleton() {
    return false;
  }

@Override
public SessionFactory getObject() {
	
	try {
		if (sessionFactoryMap==null) {
			FacesContext context = FacesContext.getCurrentInstance();
			String sessionID = "default";
			if(context!=null){
				String server =context.getExternalContext().getRequestServerName();
				getHibernateProperties().put("hibernate.default_schema", server.contains("localhost")?"public":"externo");
				sessionID = server.contains("localhost")?"public":"externo";
			}else
			getHibernateProperties().put("hibernate.default_schema", "public");
			
			System.out.println("Inicializando session factory "+sessionID+" ...");
			sessionFactoryMap = new HashMap<String, SessionFactory>();
			sessionFactoryMap.put("admin", buildSessionFactory());
			
		}
		
		return sessionFactoryMap.get("admin");
	} catch (Exception e) {
		e.printStackTrace();
		return null;
	}
}






	
}